package com.example.starseas_phone;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.starseas_phone.Adapters.AddStuListAdapter;
import com.example.starseas_phone.Entity.AddStuList;
import com.example.starseas_phone.Entity.Students;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddStuListActivity extends AppCompatActivity {

    private String TAG = "AddStuListActivity测试";

    private FloatingActionButton add_stu_list_floatbtn;
    private FloatingActionButton add_stu_list_tijiaofloatbtn;

    public static List<Students> lists = new ArrayList<>();
    private ListView listView;
    private AddStuListAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_stu_list);
        initid();
        add_stu_list_floatbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AddStuListActivity.this,AddstudentActivity.class);
                startActivity(intent);
            }
        });
        initview();
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                //首先添加一个edit实例，然后通过dialog设置显示
                AlertDialog.Builder dialog = new AlertDialog.Builder(AddStuListActivity.this);
                dialog.setTitle("是否删除该学生");
                dialog.setCancelable(false);
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(AddStuListActivity.this, "删除了"+adapter.getItem(i).getStuName(), Toast.LENGTH_SHORT).show();
                        lists.remove(i);
                        initview();
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                dialog.show();
                return false;
            }
        });
        add_stu_list_tijiaofloatbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tiiao();
            }
        });
    }

    private void initid(){
        add_stu_list_floatbtn = (FloatingActionButton) findViewById(R.id.add_stu_list_floatbtn);
        add_stu_list_tijiaofloatbtn = (FloatingActionButton)findViewById(R.id.add_stu_list_tijiaofloatbtn);
        add_stu_list_tijiaofloatbtn.setVisibility(View.GONE);
        listView = (ListView) findViewById(R.id.add_stu_list_list);
        adapter = new AddStuListAdapter(AddStuListActivity.this,R.layout.add_stu_list_listview,lists);
    }

    private void initview(){
        if (lists.size()!=0){
            add_stu_list_tijiaofloatbtn.setVisibility(View.VISIBLE);
            adapter.notifyDataSetChanged();
            listView.setAdapter(adapter);
        }else {
            add_stu_list_tijiaofloatbtn.setVisibility(View.GONE);
            adapter.notifyDataSetChanged();
            listView.setAdapter(adapter);
        }
    }

    private void tiiao(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0; i < lists.size(); i++) {
                        Students students = lists.get(i);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("StuName",students.getStuName());
                        jsonObject.put("StuAge",students.getStuAge());
                        jsonObject.put("StuSex",students.getStuSex());
                        jsonObject.put("StuPhone",students.getStuPhone());
                        jsonObject.put("StuEmail",students.getStuEmail());
                        jsonObject.put("StuCarid",students.getStuCarid());
                        jsonObject.put("ClassId",students.getStuClassId());
                        jsonObject.put("StubackTime",students.getStubackTime());
                        jsonObject.put("PoliticalLandscape",students.getPoliticalLandscape());
                        jsonObject.put("NativePlace",students.getNativePlace());
                        jsonObject.put("National",students.getNational());
                        jsonObject.put("StateOfTheSchool",students.getStateOfTheSchool());
                        jsonArray.put(jsonObject);
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("InfoJSON",jsonArray);

                    MediaType mediaType = MediaType.parse("application/json");
                    RequestBody requestBody = RequestBody.create(mediaType,"");
                    String result = URLEncoder.encode(jsonObject.getString("InfoJSON"), "utf-8");
                    String urls = Sto.NetIP+"/api/TheApplicationForm/InsertApplicationForm?token="+Sto.teachers.getToken()+"&InfoJSON="+result+"&ApplicationType=1&Status=2";
                    Log.d("url",urls);
                    Request request1 = new Request.Builder()
                            .url(urls)
                            .post(requestBody)
                            .build();
                    Response response = client.newCall(request1).execute();

                    String results = response.body().string();
                    JSONObject jsonObject1 = new JSONObject(results);
                    int code = jsonObject1.getInt("code");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (code==200){
                                Toast.makeText(AddStuListActivity.this,"申请成功",Toast.LENGTH_SHORT).show();
                                lists.clear();
                                finish();
                            }else {
                                Toast.makeText(AddStuListActivity.this,"申请失败",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    Log.d("添加学生列表",jsonArray.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    protected void onRestart() {
        initview();
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}